import { useAnvilCodeStore } from '../store/modules/code';
import componentsMixin from './componentsMixin';

export default {
  mixins: [componentsMixin],
  mounted() {
    this._loadInstance();
    this._loadFuncsInForm();
  },
  methods: {
    // 每个组件将自己的实例进行挂载
    _loadInstance() {
      const anvilCodeStore = useAnvilCodeStore();

      // inGrid用于判断表单是否在布局内，如果是则不进行挂载
      const { uuid, inGrid } = this.$attrs;
      const { name } = this.$options;
      const pageId = this.pageId || this.$attrs.pageId

      // 如果是表单，挂载在最外层,pageId是表单的prop
      if (name == 'FormRender' && pageId && !inGrid) {
        const form = {
          instance: this,
          components: [],
          pageId
        };
        anvilCodeStore.setPageForm(form);
      }

      // 需要排除加载异步组件的AsyncComponentWrapper组件以及一些完全接收attrs的组件例如element-ui组件
      const abandomComps = ['AsyncComponentWrapper'];
      const abandomPre = 'El';
      if (name && uuid && pageId && abandomComps.indexOf(name) == -1 && !name.startsWith(abandomPre)) {
        const component = {
          uuid,
          instance: this,
          prop: this.prop
        };
        if (anvilCodeStore.getPageForm(pageId)) {
          console.log('正在挂载组件', component, this);
          // 现在增加逻辑，除了有parentName字段的组件，其他组件只允许加载一份实例
          if(this.$attrs.parentName) {
            anvilCodeStore.setPageComponent(pageId, component);
          }else{
            anvilCodeStore.setUniqPageComponent(pageId, component);
          }
        }
      }
    },
    // 表单挂载自定义函数
    _loadFuncsInForm() {
      const { name } = this.$options;
      if (name == 'FormRender' && this.options) {
        if (this.options.funcs) {
          const { funcs } = this.options;
          if (funcs && funcs.length) {
            funcs.map((func) => {
              try {
                const { funcName, funcDefi } = func;
                if (funcName && funcDefi) {
                  const newFunc = eval(funcDefi);
                  this[funcName] = newFunc;
                  console.log('正在挂载表单函数', newFunc);
                }
              } catch (e) {
                console.log('挂载自定义函数失败', e);
              }
            });
          }
        }
      }
    },
  }
};
